Skip to content

a - #3

Open
deepx4344 wants to merge 1 commit into
mainfrom
dev
Open

a#3
deepx4344 wants to merge 1 commit into
mainfrom
dev

Conversation

@deepx4344

Copy link
Copy Markdown
Owner

No description provided.

@coderabbitai

coderabbitai Bot commented Feb 5, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Summary by CodeRabbit

  • New Features

    • Added a token refresh endpoint for session management
  • Bug Fixes & Improvements

    • Validation now automatically strips unknown properties from incoming requests
    • Load endpoint validation now strictly rejects unknown fields
    • Email service optimization by removing unnecessary pre-send verification step
  • API Changes

    • Response interface enhanced with generic type support for improved flexibility
  • Tests

    • Expanded test coverage for authentication workflows and load controller operations

Walkthrough

This PR introduces validation enhancements (stripUnknown option in Joi, stricter load schema), adds a new POST /refresh endpoint to auth routes, removes email service verification step, makes the ApiResponse type generic, refactors service imports, and adds comprehensive unit and integration test coverage for auth and load functionality.

Changes

Cohort / File(s) Summary
Auth Endpoint & Routing
src/controllers/auth.ts, src/routes/auth.ts
Added new POST /refresh endpoint wired to refresh controller; minor formatting adjustments in existing route declarations and controller response formatting.
Validation & Middleware
src/middlewares/joiValidation.ts, src/validations/load.ts
Introduced stripUnknown: true to default Joi validation options; changed loadSchema to reject unknown fields (unknown(false)) instead of allowing them.
Service Layer & Imports
src/services/emailService.ts, src/services/loadService.ts
Removed transporter.verify() call from email service; changed loadService import from test.js to load.js for Tests class.
Type System
src/types/index.ts
Made ApiResponse interface generic with default type parameter T = unknown; updated data and datas fields from string/string[] to T/T[]; changed testSchema import path from test.js to load.js.
Test Reorganization & New Coverage
tests/auth.test.ts, tests/auth/auth.test.ts, tests/unit/controllers/authController.test.ts, tests/unit/controllers/loadController.test.ts
Removed monolithic tests/auth.test.ts; added comprehensive integration test suite in tests/auth/auth.test.ts with helper functions for register/verify/login flows; introduced unit tests for auth controller (register, login, verify, refresh, me, logout) and load controller (startLoad).

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

🐰 A refresh endpoint hops into view,
Validations grow stricter—unknown fields bid adieu!
Tests multiply, covering auth's sacred ground,
Generic responses dance without a sound,
The API evolves, more robust and true! ✨

🚥 Pre-merge checks | ✅ 1 | ❌ 2
❌ Failed checks (2 inconclusive)
Check name Status Explanation Resolution
Title check ❓ Inconclusive The pull request title 'a' is vague and generic, providing no meaningful information about the substantial changes made across multiple files and features. Replace the title with a descriptive summary of the main changes, such as 'Add refresh endpoint, improve validation, and refactor tests' or identify the primary objective of this PR.
Description check ❓ Inconclusive No pull request description was provided by the author, making it impossible to assess whether the description relates to the changeset. Add a pull request description that explains the purpose, scope, and rationale for the changes made across auth, validation, and test files.
✅ Passed checks (1 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch dev

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 10

🤖 Fix all issues with AI agents
In `@src/middlewares/joiValidation.ts`:
- Line 10: The middleware default options set stripUnknown: true which removes
unknown properties before Joi runs, so schemas that use .unknown(false) (e.g.
loadSchema used via validateSchema(loadSchema) in src/routes/load.ts) never get
an "unknown field" error; fix by either removing stripUnknown: true from the
default Joi.ValidationOptions in the middleware (options variable in
joiValidation.ts) or make validateSchema accept/forward custom options and
update the call site validateSchema(loadSchema) to pass { stripUnknown: false }
for strict schemas like loadSchema so Joi's .unknown(false) can reject extra
keys.

In `@src/routes/auth.ts`:
- Line 21: The /refresh route currently lacks the authlimiter middleware and the
refresh controller (function refresh in src/controllers/auth.ts) dereferences
req.signedCookies["tokens"].refreshToken without checking for tokens, which can
throw a TypeError and allows brute forcing; update the router.post("/refresh",
refresh) registration to include the existing authlimiter middleware (same as
used for /login and /register) and add a guard at the start of the refresh
controller to validate presence of req.signedCookies["tokens"] and
tokens.refreshToken, returning a 401 JSON API response (using createAPIResponse)
if missing; ensure the change references the refresh handler and authlimiter
symbol so the middleware and null-check are applied consistently.

In `@src/types/index.ts`:
- Around line 23-30: The ApiResponseinput<T> generic isn’t propagated because
createAPIResponse is not generic; update the createAPIResponse function to
accept a generic type parameter (e.g., function createAPIResponse<T>(input:
ApiResponseinput<T>)) and have it return the appropriately typed response
including the added timestamp so callers receive the correct generic typing for
data/datas; reference the ApiResponseinput and createAPIResponse symbols when
making this change.

In `@src/validations/load.ts`:
- Line 15: The unknown(false) check in loadSchema is ineffective because the
middleware in joiValidation.ts currently strips unknown properties by default;
update the call site that applies validateSchema(loadSchema) to pass an override
option { stripUnknown: false } (or alternatively remove/disable stripUnknown in
joiValidation.ts) so that unknown(false) can actually reject unknown fields;
reference the loadSchema defined in src/validations/load.ts and the
validateSchema(...) usage in your route/middleware to apply the fix.

In `@tests/auth/auth.test.ts`:
- Around line 69-85: Fix the minor formatting in the test hooks by adding a
space after the comma in the timeout parameter for both beforeAll and afterAll;
locate the beforeAll(...) and afterAll(...) invocations (which call connectDB(),
use mongoose.connection.db to deleteMany on the "users" collection with
testEmail, and call mongoose.disconnect()) and change the timeout argument
formatting from "},20000);" to "}, 20000);" in both places.
- Around line 87-115: The tests are dependent on shared state; make them
independent by either (A) moving the shared setup into a beforeAll that calls
registerUser() (and verifyUser() if needed) and then querying Users.findOne({
email: testEmail }) in tests, or (B, preferred) have each it() create its own
user by calling registerUser() with a unique email and, when needed, calling
verifyUser() or loginUser() within the same test so registerUser, verifyUser,
and loginUser are invoked locally; update assertions to use the local email and
keep Users.findOne({ email: testEmail }) references consistent with the chosen
approach.

In `@tests/unit/controllers/authController.test.ts`:
- Around line 45-57: The test for authController.register lacks an assertion
ensuring the next error handler wasn't invoked; update the test in
authController.test.ts to assert that the jest mock next was not called after
invoking authController.register (and apply the same pattern to other tests in
this file), i.e. after awaiting flushPromises verify next was not called (or
explicitly called with expected error in error-path tests) alongside the
existing assertions for registerMock, res.status and res.json to ensure error
propagation behavior is covered.
- Around line 1-28: Add a beforeEach block to clear/reset the module-level mocks
so tests don't leak state: call jest.clearAllMocks() and jest.resetAllMocks()
(and optionally jest.restoreAllMocks()) in a beforeEach placed in this test file
to reset registerMock, loginMock, verifyMock, logoutMock, refreshMock, meMock
and the AuthServiceMock between tests; this ensures each test starts with fresh
call histories and implementations for those mocks.

In `@tests/unit/controllers/loadController.test.ts`:
- Around line 24-49: Add error-path unit tests for loadController.startLoad by
mocking createTest (createTestMock) to reject with an Error and asserting that
startLoad calls next with that error and does not send a success response;
specifically, add a test that stubs createTestMock.mockRejectedValueOnce(new
Error("boom")), calls loadController.startLoad(req, res, next), awaits
flushPromises(), then expect(next).toHaveBeenCalledWith(expect.any(Error)) and
expect(res.status).not.toHaveBeenCalled() /
expect(res.json).not.toHaveBeenCalled(); also add a variant that verifies proper
handling of rejection payloads (e.g., an Error with a message) so error details
flow to next.
- Around line 37-38: The test currently calls loadController.startLoad(req, res,
next) and then uses flushPromises(); instead await the controller invocation
directly: call and await loadController.startLoad(req, res, next) (removing the
flushPromises() usage) so the test waits for the actual Promise returned by
startLoad (likely from asyncHandler) to resolve; update the test to remove or
replace the flushPromises() call and ensure assertions run after the awaited
startLoad completes.
📜 Review details

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b2bff96 and fdf2a3d.

📒 Files selected for processing (12)
  • src/controllers/auth.ts
  • src/middlewares/joiValidation.ts
  • src/models/load.ts
  • src/routes/auth.ts
  • src/services/emailService.ts
  • src/services/loadService.ts
  • src/types/index.ts
  • src/validations/load.ts
  • tests/auth.test.ts
  • tests/auth/auth.test.ts
  • tests/unit/controllers/authController.test.ts
  • tests/unit/controllers/loadController.test.ts
💤 Files with no reviewable changes (2)
  • src/services/emailService.ts
  • tests/auth.test.ts
🧰 Additional context used
🧬 Code graph analysis (4)
src/services/loadService.ts (1)
src/services/loadervice.ts (1)
  • loadService (3-8)
src/types/index.ts (1)
src/utils/index.ts (1)
  • createAPIResponse (14-19)
tests/auth/auth.test.ts (1)
src/utils/jwt.ts (1)
  • generateToken (8-29)
src/routes/auth.ts (1)
src/controllers/auth.ts (2)
  • logout (36-42)
  • refresh (44-50)
🔇 Additional comments (7)
src/services/loadService.ts (1)

3-3: LGTM!

The import path change from ../models/test.js to ../models/load.js aligns with the broader refactor to consolidate load-related models.

src/types/index.ts (1)

3-3: LGTM!

Import path update aligns with the model consolidation.

src/controllers/auth.ts (1)

49-49: LGTM!

Minor formatting fix for consistency.

tests/unit/controllers/authController.test.ts (2)

32-43: LGTM!

The createRes helper provides a well-structured chainable mock response, and flushPromises correctly flushes the microtask queue for async controller handlers.


59-137: LGTM!

The remaining test cases (login, verify, refresh, me, logout) are well-structured and correctly verify the expected interactions with the mocked service, response status codes, cookies, and response methods.

tests/auth/auth.test.ts (2)

1-17: LGTM!

The setup correctly mocks the email service before dynamically importing the application modules, ensuring the mock is in place when the modules are loaded. Using jest.unstable_mockModule with dynamic imports is the proper pattern for ESM mocking.


19-67: LGTM!

The helper functions encapsulate the authentication workflow steps effectively. The verification token generation correctly uses the JWT configuration from the environment.

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.

schema: Joi.Schema,
property: "body" | "query" | "params" = "body",
options: Joi.ValidationOptions = { abortEarly: false }
options: Joi.ValidationOptions = { abortEarly: false, stripUnknown: true },

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Search for schemas using unknown(false)
rg -n 'unknown\s*\(\s*false\s*\)' --type ts

Repository: deepx4344/SurgeTest

Length of output: 108


🏁 Script executed:

#!/bin/bash
# Check the joiValidation.ts file
echo "=== joiValidation.ts ==="
cat -n src/middlewares/joiValidation.ts | head -50

echo -e "\n=== load.ts schema context ==="
cat -n src/validations/load.ts

Repository: deepx4344/SurgeTest

Length of output: 1797


🌐 Web query:

Joi stripUnknown precedence over unknown(false) validation order

💡 Result:

In Joi, stripUnknown effectively wins over unknown(false) (the default) for object keys:

  • If you validate an object with extra keys using unknown(false), Joi would normally raise object.unknown (“is not allowed”). But if you also set stripUnknown (e.g. { stripUnknown: true } or { stripUnknown: { objects: true } }), Joi will remove the unknown keys and not error. This is shown in the Joi repo issue repro: the same schema that errors without stripUnknown returns { error: null, value: <stripped> } with stripUnknown enabled. [1]
  • object.unknown([allow]) controls whether unknown keys are allowed/ignored at the schema level. [2]
  • stripUnknown is a validation preference that deletes unknown keys from the validated value. [3][4]
  • Also, stripUnknown removal happens even if the schema allows unknown keys via object().unknown()—it still strips them when stripUnknown is on (the “unexpected interaction” noted in the same issue). [1]

So, validation “order/precedence” for this behavior is: when stripUnknown is enabled, unknown keys are stripped instead of producing an object.unknown error, regardless of unknown(false) (and historically even regardless of unknown(true)/.unknown()). [1]

Practical takeaway

  • Want an error on extra keys? Don’t use stripUnknown; keep unknown(false) (default).
  • Want to silently drop extra keys? Use stripUnknown (you can keep unknown(false); it won’t error). [1][3]

Sources: [1] [2] [3] [4]


🏁 Script executed:

#!/bin/bash
# Search for usage of validateSchema with loadSchema
echo "=== Looking for validateSchema usage ==="
rg -n 'validateSchema' --type ts -A 3 -B 1

echo -e "\n=== Looking for loadSchema usage ==="
rg -n 'loadSchema' --type ts -A 2 -B 1

Repository: deepx4344/SurgeTest

Length of output: 2422


stripUnknown: true default makes unknown(false) schemas ineffective.

At line 9 of src/routes/load.ts, validateSchema(loadSchema) is called without custom options, using the middleware's default stripUnknown: true. Since loadSchema explicitly sets .unknown(false) to reject unknown keys, but the middleware strips unknown keys before schema validation, the schema's validation rule never gets triggered. Unknown properties are silently removed instead of returning a validation error.

If schemas like loadSchema are intentionally strict about rejecting unknown fields, either:

  1. Remove stripUnknown: true from the middleware defaults, or
  2. Pass custom options { stripUnknown: false } when calling validateSchema(loadSchema) (and other strict schemas)
🤖 Prompt for AI Agents
In `@src/middlewares/joiValidation.ts` at line 10, The middleware default options
set stripUnknown: true which removes unknown properties before Joi runs, so
schemas that use .unknown(false) (e.g. loadSchema used via
validateSchema(loadSchema) in src/routes/load.ts) never get an "unknown field"
error; fix by either removing stripUnknown: true from the default
Joi.ValidationOptions in the middleware (options variable in joiValidation.ts)
or make validateSchema accept/forward custom options and update the call site
validateSchema(loadSchema) to pass { stripUnknown: false } for strict schemas
like loadSchema so Joi's .unknown(false) can reject extra keys.

Comment thread src/routes/auth.ts
router.get("/verify/:token", verify);
router.post("/logout",authMiddleware, logout);
router.post("/logout", authMiddleware, logout);
router.post("/refresh", refresh);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Missing rate limiting and no guard against missing cookies.

The /refresh endpoint lacks the authlimiter middleware that protects /login and /register. This could allow attackers to abuse the refresh mechanism.

Additionally, the refresh controller (in src/controllers/auth.ts, lines 44-49) accesses req.signedCookies["tokens"].refreshToken without checking if tokens exists. If the cookie is missing, this will throw a TypeError.

Consider:

  1. Adding authlimiter to prevent abuse
  2. Adding validation for cookie presence (either via middleware or in the controller)
Suggested fix
-router.post("/refresh", refresh);
+router.post("/refresh", authlimiter, refresh);

And in the controller, add a guard:

const tokens: Tokens | undefined = req.signedCookies["tokens"];
if (!tokens?.refreshToken) {
  return res.status(401).json(createAPIResponse({
    success: false,
    message: "No refresh token provided",
  }));
}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
router.post("/refresh", refresh);
router.post("/refresh", authlimiter, refresh);
🤖 Prompt for AI Agents
In `@src/routes/auth.ts` at line 21, The /refresh route currently lacks the
authlimiter middleware and the refresh controller (function refresh in
src/controllers/auth.ts) dereferences req.signedCookies["tokens"].refreshToken
without checking for tokens, which can throw a TypeError and allows brute
forcing; update the router.post("/refresh", refresh) registration to include the
existing authlimiter middleware (same as used for /login and /register) and add
a guard at the start of the refresh controller to validate presence of
req.signedCookies["tokens"] and tokens.refreshToken, returning a 401 JSON API
response (using createAPIResponse) if missing; ensure the change references the
refresh handler and authlimiter symbol so the middleware and null-check are
applied consistently.

Comment thread src/types/index.ts
Comment on lines +23 to +30
export interface ApiResponseinput<T = unknown> {
success: boolean;
message: string;
token?: string;
tokens?: Tokens;
user?: User;
data?: string;
datas?: string[]
data?: T;
datas?: T[];

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

Good improvement: Generic interface enhances type safety.

The generic ApiResponseinput<T> allows for typed data and datas fields. However, for consumers to fully benefit, createAPIResponse in src/utils/index.ts (line 13-18) should also be made generic:

function createAPIResponse<T>(input: ApiResponseinput<T>) {
  return {
    ...input,
    timestamp: new Date().toISOString(),
  };
}

Without this, the generic parameter won't propagate through the helper function.

🤖 Prompt for AI Agents
In `@src/types/index.ts` around lines 23 - 30, The ApiResponseinput<T> generic
isn’t propagated because createAPIResponse is not generic; update the
createAPIResponse function to accept a generic type parameter (e.g., function
createAPIResponse<T>(input: ApiResponseinput<T>)) and have it return the
appropriately typed response including the added timestamp so callers receive
the correct generic typing for data/datas; reference the ApiResponseinput and
createAPIResponse symbols when making this change.

Comment thread src/validations/load.ts
concurrency: Joi.number().min(1).default(10),
duration: Joi.number().min(1).default(30),
}).unknown(true);
}).unknown(false);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

This unknown(false) is effectively a no-op due to middleware defaults.

The intent to reject unknown fields is good for strict validation. However, since joiValidation.ts now defaults to stripUnknown: true, unknown properties are stripped before this check runs, meaning this constraint will never trigger a validation error.

To enforce strict rejection of unknown fields, either:

  1. Remove stripUnknown from the middleware defaults, or
  2. Pass { stripUnknown: false } when calling validateSchema(loadSchema) in the route
🤖 Prompt for AI Agents
In `@src/validations/load.ts` at line 15, The unknown(false) check in loadSchema
is ineffective because the middleware in joiValidation.ts currently strips
unknown properties by default; update the call site that applies
validateSchema(loadSchema) to pass an override option { stripUnknown: false }
(or alternatively remove/disable stripUnknown in joiValidation.ts) so that
unknown(false) can actually reject unknown fields; reference the loadSchema
defined in src/validations/load.ts and the validateSchema(...) usage in your
route/middleware to apply the fix.

Comment thread tests/auth/auth.test.ts
Comment on lines +69 to +85
beforeAll(async () => {
await connectDB();
if (mongoose.connection.db) {
await mongoose.connection.db
.collection("users")
.deleteMany({ email: testEmail });
}
},20000);

afterAll(async () => {
if (mongoose.connection.db) {
await mongoose.connection.db
.collection("users")
.deleteMany({ email: testEmail });
}
await mongoose.disconnect();
},20000);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Minor formatting: Add space after comma in timeout parameter.

🔧 Proposed fix
-},20000);
+}, 20000);

Apply to both beforeAll (line 76) and afterAll (line 85).

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
beforeAll(async () => {
await connectDB();
if (mongoose.connection.db) {
await mongoose.connection.db
.collection("users")
.deleteMany({ email: testEmail });
}
},20000);
afterAll(async () => {
if (mongoose.connection.db) {
await mongoose.connection.db
.collection("users")
.deleteMany({ email: testEmail });
}
await mongoose.disconnect();
},20000);
beforeAll(async () => {
await connectDB();
if (mongoose.connection.db) {
await mongoose.connection.db
.collection("users")
.deleteMany({ email: testEmail });
}
}, 20000);
afterAll(async () => {
if (mongoose.connection.db) {
await mongoose.connection.db
.collection("users")
.deleteMany({ email: testEmail });
}
await mongoose.disconnect();
}, 20000);
🤖 Prompt for AI Agents
In `@tests/auth/auth.test.ts` around lines 69 - 85, Fix the minor formatting in
the test hooks by adding a space after the comma in the timeout parameter for
both beforeAll and afterAll; locate the beforeAll(...) and afterAll(...)
invocations (which call connectDB(), use mongoose.connection.db to deleteMany on
the "users" collection with testEmail, and call mongoose.disconnect()) and
change the timeout argument formatting from "},20000);" to "}, 20000);" in both
places.

Comment thread tests/auth/auth.test.ts
Comment on lines +87 to +115
describe("Auth routes", () => {
it("registers a new user", async () => {
const registerResponse = await registerUser();
expect(registerResponse.body).toMatchObject({
success: true,
message: "User Created Successfully",
});

const user = await Users.findOne({ email: testEmail }).lean();
expect(user).toBeTruthy();
expect(user?.verified).toBe(false);
});

it("verifies a registered user", async () => {
await verifyUser();

const verifiedUser = await Users.findOne({ email: testEmail }).lean();
expect(verifiedUser?.verified).toBe(true);
});

it("logs in a verified user", async () => {
const loginResponse = await loginUser();
expect(loginResponse.body).toMatchObject({
success: true,
message: "User Logged In Successfully",
});
expect(loginResponse.headers["set-cookie"]).toBeDefined();
});
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Tests are sequentially dependent, which may cause cascading failures.

The tests rely on shared state: "verifies a registered user" assumes "registers a new user" ran first, and "logs in a verified user" assumes verification completed. If any earlier test fails or is skipped, subsequent tests will fail with misleading errors.

Consider moving the prerequisite steps into the test setup or using explicit dependencies.

♻️ Proposed refactor: Move shared setup into beforeAll or make tests independent

Option 1: Move registration to beforeAll for dependent tests

+let isRegistered = false;
+let isVerified = false;
+
 describe("Auth routes", () => {
+  beforeAll(async () => {
+    await registerUser();
+    isRegistered = true;
+    await verifyUser();
+    isVerified = true;
+  });
+
   it("registers a new user", async () => {
-    const registerResponse = await registerUser();
-    expect(registerResponse.body).toMatchObject({
+    // Registration already done in beforeAll, verify the state
+    const user = await Users.findOne({ email: testEmail }).lean();
+    expect(user).toBeTruthy();
+  });

Option 2: Make each test fully independent (preferred for isolation)

Each test registers its own user with a unique email, ensuring complete isolation.

🤖 Prompt for AI Agents
In `@tests/auth/auth.test.ts` around lines 87 - 115, The tests are dependent on
shared state; make them independent by either (A) moving the shared setup into a
beforeAll that calls registerUser() (and verifyUser() if needed) and then
querying Users.findOne({ email: testEmail }) in tests, or (B, preferred) have
each it() create its own user by calling registerUser() with a unique email and,
when needed, calling verifyUser() or loginUser() within the same test so
registerUser, verifyUser, and loginUser are invoked locally; update assertions
to use the local email and keep Users.findOne({ email: testEmail }) references
consistent with the chosen approach.

Comment on lines +1 to +28
import { jest, describe, it, expect } from "@jest/globals";

const registerMock = jest.fn<any>().mockResolvedValue(undefined);
const loginMock = jest.fn<any>().mockResolvedValue({
accessToken: "access-token",
refreshToken: "refresh-token",
});
const verifyMock = jest.fn<any>().mockResolvedValue(undefined);
const logoutMock = jest.fn<any>().mockResolvedValue(undefined);
const refreshMock = jest.fn<any>().mockResolvedValue("new-access-token");
const meMock = jest.fn<any>().mockResolvedValue({
id: "user-id",
email: "user@example.com",
paid: false,
});

const AuthServiceMock = jest.fn().mockImplementation(() => ({
register: registerMock,
login: loginMock,
verify: verifyMock,
logout: logoutMock,
refresh: refreshMock,
me: meMock,
}));

jest.unstable_mockModule("../../../src/services/authService.js", () => ({
default: AuthServiceMock,
}));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

Mocks are not reset between tests, risking test pollution.

The mock functions are defined at module scope and not cleared between tests. If one test modifies mock behavior or accumulates call history, subsequent tests may produce false positives or negatives.

♻️ Proposed fix: Add beforeEach to reset mocks
 const authController = await import("../../../src/controllers/auth.js");
 
+import { beforeEach } from "@jest/globals";
+
+beforeEach(() => {
+  jest.clearAllMocks();
+});
+
 const createRes = () => {
🤖 Prompt for AI Agents
In `@tests/unit/controllers/authController.test.ts` around lines 1 - 28, Add a
beforeEach block to clear/reset the module-level mocks so tests don't leak
state: call jest.clearAllMocks() and jest.resetAllMocks() (and optionally
jest.restoreAllMocks()) in a beforeEach placed in this test file to reset
registerMock, loginMock, verifyMock, logoutMock, refreshMock, meMock and the
AuthServiceMock between tests; this ensures each test starts with fresh call
histories and implementations for those mocks.

Comment on lines +45 to +57
describe("Auth controller", () => {
it("registers a user", async () => {
const req: any = { body: { email: "user@example.com", password: "Pass.!1" } };
const res = createRes();
const next = jest.fn();

authController.register(req, res, next);
await flushPromises();

expect(registerMock).toHaveBeenCalledWith("user@example.com", "Pass.!1");
expect(res.status).toHaveBeenCalledWith(201);
expect(res.json).toHaveBeenCalled();
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

Missing assertion on next function for error propagation.

The next function is created but never verified. If the controller inadvertently calls next(error), the test would still pass. Consider asserting that next was not called (or called with specific errors for error-path tests).

♻️ Proposed fix: Add assertion for next
     expect(registerMock).toHaveBeenCalledWith("user@example.com", "Pass.!1");
     expect(res.status).toHaveBeenCalledWith(201);
     expect(res.json).toHaveBeenCalled();
+    expect(next).not.toHaveBeenCalled();
   });

Apply the same pattern to all other test cases.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
describe("Auth controller", () => {
it("registers a user", async () => {
const req: any = { body: { email: "user@example.com", password: "Pass.!1" } };
const res = createRes();
const next = jest.fn();
authController.register(req, res, next);
await flushPromises();
expect(registerMock).toHaveBeenCalledWith("user@example.com", "Pass.!1");
expect(res.status).toHaveBeenCalledWith(201);
expect(res.json).toHaveBeenCalled();
});
describe("Auth controller", () => {
it("registers a user", async () => {
const req: any = { body: { email: "user@example.com", password: "Pass.!1" } };
const res = createRes();
const next = jest.fn();
authController.register(req, res, next);
await flushPromises();
expect(registerMock).toHaveBeenCalledWith("user@example.com", "Pass.!1");
expect(res.status).toHaveBeenCalledWith(201);
expect(res.json).toHaveBeenCalled();
expect(next).not.toHaveBeenCalled();
});
🤖 Prompt for AI Agents
In `@tests/unit/controllers/authController.test.ts` around lines 45 - 57, The test
for authController.register lacks an assertion ensuring the next error handler
wasn't invoked; update the test in authController.test.ts to assert that the
jest mock next was not called after invoking authController.register (and apply
the same pattern to other tests in this file), i.e. after awaiting flushPromises
verify next was not called (or explicitly called with expected error in
error-path tests) alongside the existing assertions for registerMock, res.status
and res.json to ensure error propagation behavior is covered.

Comment on lines +24 to +49
describe("Load controller", () => {
it("starts a load test", async () => {
const req: any = {
body: {
url: "https://example.com",
method: "GET",
concurrency: 5,
duration: 10,
},
};
const res = createRes();
const next = jest.fn();

loadController.startLoad(req, res, next);
await flushPromises();

expect(createTestMock).toHaveBeenCalledWith(req.body);
expect(res.status).toHaveBeenCalledWith(202);
expect(res.json).toHaveBeenCalledWith(
expect.objectContaining({
success: true,
message: "Task created successfully",
data: "test-id",
}),
);
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

Test coverage is limited to the happy path.

Consider adding tests for error scenarios:

  • What happens when createTest rejects?
  • Does the next function get called with the error?

Would you like me to generate additional test cases for error handling?

🤖 Prompt for AI Agents
In `@tests/unit/controllers/loadController.test.ts` around lines 24 - 49, Add
error-path unit tests for loadController.startLoad by mocking createTest
(createTestMock) to reject with an Error and asserting that startLoad calls next
with that error and does not send a success response; specifically, add a test
that stubs createTestMock.mockRejectedValueOnce(new Error("boom")), calls
loadController.startLoad(req, res, next), awaits flushPromises(), then
expect(next).toHaveBeenCalledWith(expect.any(Error)) and
expect(res.status).not.toHaveBeenCalled() /
expect(res.json).not.toHaveBeenCalled(); also add a variant that verifies proper
handling of rejection payloads (e.g., an Error with a message) so error details
flow to next.

Comment on lines +37 to +38
loadController.startLoad(req, res, next);
await flushPromises();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

Consider awaiting the controller call directly.

The flushPromises() pattern works but can be fragile. If startLoad returns a Promise (which it likely does via asyncHandler), awaiting it directly is more robust:

-    loadController.startLoad(req, res, next);
-    await flushPromises();
+    await loadController.startLoad(req, res, next);

This ensures the test waits for the actual promise to resolve rather than relying on microtask timing.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
loadController.startLoad(req, res, next);
await flushPromises();
await loadController.startLoad(req, res, next);
🤖 Prompt for AI Agents
In `@tests/unit/controllers/loadController.test.ts` around lines 37 - 38, The test
currently calls loadController.startLoad(req, res, next) and then uses
flushPromises(); instead await the controller invocation directly: call and
await loadController.startLoad(req, res, next) (removing the flushPromises()
usage) so the test waits for the actual Promise returned by startLoad (likely
from asyncHandler) to resolve; update the test to remove or replace the
flushPromises() call and ensure assertions run after the awaited startLoad
completes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant